/**
 * Session Store
 * 
 * 使用 Zustand 管理 session 状态
 */

import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import type { Session, Message } from '@/api/session';
import * as sessionApi from '@/api/session';

// ============================================================================
// 类型定义
// ============================================================================

interface SessionStore {
  // 状态
  currentSession: Session | null;
  sessions: Session[];
  loading: boolean;
  error: string | null;

  // Session 操作
  createSession: (title?: string, subAgentId?: string) => Promise<Session>;
  loadSession: (sessionId: string) => Promise<void>;
  deleteSession: (sessionId: string) => Promise<void>;
  loadSessions: () => Promise<void>;
  setCurrentSession: (session: Session | null) => void;
  renameSession: (sessionId: string, newTitle: string) => Promise<void>;

  // Message 操作
  addMessage: (
    sessionId: string,
    role: 'user' | 'assistant' | 'system',
    content: string,
    metadata?: Record<string, any>,
    subAgentId?: string
  ) => Promise<Message>;

  // 归档操作
  archiveSession: (sessionId: string) => Promise<void>;

  // 工具方法
  clearError: () => void;
  reset: () => void;
}

// ============================================================================
// Store 实现
// ============================================================================

export const useSessionStore = create<SessionStore>()(
  persist(
    (set) => ({
      // 初始状态
      currentSession: null,
      sessions: [],
      loading: false,
      error: null,

      // 创建新 session
      createSession: async (title?: string, subAgentId?: string) => {
        set({ loading: true, error: null });

        try {
          const session = await sessionApi.createSession({
            title: title || '新对话',
            subAgentId,
            metadata: {
              createdBy: 'user',
              source: 'web',
            },
          });

          set((state) => ({
            currentSession: session,
            sessions: [session, ...state.sessions],
            loading: false,
          }));

          return session;
        } catch (error) {
          const errorMessage = error instanceof Error ? error.message : 'Failed to create session';
          set({ error: errorMessage, loading: false });
          throw error;
        }
      },

      // 加载 session
      loadSession: async (sessionId: string) => {
        set({ loading: true, error: null });

        try {
          const session = await sessionApi.getSession(sessionId);

          set({
            currentSession: session,
            loading: false,
          });
        } catch (error) {
          const errorMessage = error instanceof Error ? error.message : 'Failed to load session';
          set({ error: errorMessage, loading: false });
          throw error;
        }
      },

      // 删除 session
      deleteSession: async (sessionId: string) => {
        set({ loading: true, error: null });

        try {
          await sessionApi.deleteSession(sessionId);

          set((state) => ({
            sessions: state.sessions.filter((s) => s.id !== sessionId),
            currentSession: state.currentSession?.id === sessionId ? null : state.currentSession,
            loading: false,
          }));
        } catch (error) {
          const errorMessage = error instanceof Error ? error.message : 'Failed to delete session';
          set({ error: errorMessage, loading: false });
          throw error;
        }
      },

      // 加载所有 sessions
      loadSessions: async () => {
        set({ loading: true, error: null });

        try {
          const result = await sessionApi.listSessions({
            limit: 50,
            sortBy: 'updatedAt',
            sortOrder: 'desc',
          });

          set({
            sessions: result.sessions,
            loading: false,
          });
        } catch (error) {
          const errorMessage = error instanceof Error ? error.message : 'Failed to load sessions';
          set({ error: errorMessage, loading: false });
          throw error;
        }
      },

      // 设置当前 session
      setCurrentSession: (session: Session | null) => {
        set({ currentSession: session });
      },

      // 添加消息
      addMessage: async (
        sessionId: string,
        role: 'user' | 'assistant' | 'system',
        content: string,
        metadata?: Record<string, any>,
        subAgentId?: string
      ) => {
        try {
          const message = await sessionApi.addMessage(sessionId, {
            role,
            content,
            metadata,
            subAgentId,
          });

          // 更新当前 session 的消息列表
          set((state) => {
            if (state.currentSession?.id === sessionId) {
              return {
                currentSession: {
                  ...state.currentSession,
                  messages: [...state.currentSession.messages, message],
                  updatedAt: new Date().toISOString(),
                },
              };
            }
            return state;
          });

          return message;
        } catch (error) {
          const errorMessage = error instanceof Error ? error.message : 'Failed to add message';
          set({ error: errorMessage });
          throw error;
        }
      },

      // 重命名 session
      renameSession: async (sessionId: string, newTitle: string) => {
        set({ loading: true, error: null });

        try {
          // 注意：这里假设后端有 updateSession API，如果没有，需要添加
          // 临时实现：直接更新本地状态
          set((state) => ({
            sessions: state.sessions.map((s) =>
              s.id === sessionId ? { ...s, title: newTitle, updatedAt: new Date().toISOString() } : s
            ),
            currentSession: state.currentSession?.id === sessionId 
              ? { ...state.currentSession, title: newTitle, updatedAt: new Date().toISOString() }
              : state.currentSession,
            loading: false,
          }));
        } catch (error) {
          const errorMessage = error instanceof Error ? error.message : 'Failed to rename session';
          set({ error: errorMessage, loading: false });
          throw error;
        }
      },

      // 归档 session
      archiveSession: async (sessionId: string) => {
        set({ loading: true, error: null });

        try {
          await sessionApi.archiveSession(sessionId);

          set((state) => ({
            sessions: state.sessions.map((s) =>
              s.id === sessionId ? { ...s, archived: true } : s
            ),
            loading: false,
          }));
        } catch (error) {
          const errorMessage = error instanceof Error ? error.message : 'Failed to archive session';
          set({ error: errorMessage, loading: false });
          throw error;
        }
      },

      // 清除错误
      clearError: () => {
        set({ error: null });
      },

      // 重置状态
      reset: () => {
        set({
          currentSession: null,
          sessions: [],
          loading: false,
          error: null,
        });
      },
    }),
    {
      name: 'session-storage',
      partialize: (state) => ({
        // 只持久化当前 session ID，不持久化完整的 session 数据
        currentSessionId: state.currentSession?.id,
      }),
    }
  )
);

// ============================================================================
// Selectors
// ============================================================================

/**
 * 获取当前 session 的消息数量
 */
export const selectMessageCount = (state: SessionStore) =>
  state.currentSession?.messages.length || 0;

/**
 * 获取最近的 sessions
 */
export const selectRecentSessions = (state: SessionStore) =>
  state.sessions.slice(0, 10);

/**
 * 检查是否有活动的 session
 */
export const selectHasActiveSession = (state: SessionStore) =>
  state.currentSession !== null;

